package com.qk.interceptor;

import com.qk.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1.获取请求路径
        String url = request.getRequestURI();
        //2.判断请求路径是否为登录接口
        if (url.contains("/login")) {

            return true;
        }
        //3.获取token
        String token = request.getHeader("token");
        //4.判断token是否为空
        if (token == null || token.isEmpty()) {
            response.setStatus(401);
            return true;
        }
        //5.解析令牌,出错报401
        try {
            JwtUtils.parseToken(token);
        } catch (Exception e) {
            response.setStatus(401);
            return true;
        }
        //6.放行
       return true;
    }
}
